﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Net.Http.Headers;
using System.Security.Claims;
using System.Text;
using System.Text.Encodings.Web;
using System.Threading.Tasks;

namespace LCS.Api.Authorization
{
    /// <summary>
    /// 基本验证逻辑从数据库读取
    /// </summary>
    public class BasicAuthenticationHandler : AuthenticationHandler<AuthenticationSchemeOptions>
    {
        //private readonly IUserService _userService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="options"></param>
        /// <param name="logger"></param>
        /// <param name="encoder"></param>
        /// <param name="clock"></param>
        public BasicAuthenticationHandler(
            IOptionsMonitor<AuthenticationSchemeOptions> options,
            ILoggerFactory logger,
            UrlEncoder encoder,
            ISystemClock clock
            //,IUserService userService
            )
            : base(options, logger, encoder, clock)
        {
            //_userService = userService;
        }

        /// <summary>
        /// 基本验证逻辑从数据库读取
        /// </summary>
        /// <returns></returns>
        /// <exception cref="System.NotImplementedException"></exception>
        protected override Task<AuthenticateResult> HandleAuthenticateAsync()
        {
            //User user;

            try
            {
                var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]);
                var credentialBytes = Convert.FromBase64String(authHeader.Parameter);
                var credentials = Encoding.UTF8.GetString(credentialBytes).Split(new[] { ':' }, 2);
                var username = credentials[0];
                var password = credentials[1];
                //user = await _userService.Authenticate(username, password);
            }
            catch
            {
                return Task.FromResult(AuthenticateResult.Fail("Error Occured.Authorization failed."));
            }

            //if (user == null)
            //    return Task.FromResult(AuthenticateResult.Fail("Invalid Credentials"));



            var claims = new[]{
                new Claim(ClaimTypes.NameIdentifier, "userid"),
                new Claim(ClaimTypes.Name, "userName"),
              };

            var identity = new ClaimsIdentity(claims, Scheme.Name);
            var principal = new ClaimsPrincipal(identity);

            var ticket = new AuthenticationTicket(principal, Scheme.Name);

            return Task.FromResult(AuthenticateResult.Success(ticket));
        }
    }
}
